package cn.sdjzu.exercise;

import java.io.IOException;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;

public class AdjustSeatActivity extends TransmissionActivity implements OnTouchListener {

	private ImageButton mUpBtn;
	private ImageButton mDownBtn;
	//private ExerciseApp app ;
	public static String fromWhich;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ExerciseApp.getInstance().addActivity(this);
		setContentView(R.layout.adjust_seat);
		//app = (ExerciseApp) AdjustSeatActivity.this.getApplication();	
		mUpBtn = (ImageButton) this
				.findViewById(R.id.adjust_seat_up);
		mDownBtn = (ImageButton) this.findViewById(R.id.adjust_seat_down);
		mUpBtn.setOnTouchListener(this);
		mDownBtn.setOnTouchListener(this);
	}

	@Override
	public void onBackPressed() {
		if ("exercise".equals(fromWhich)) {
			Intent intentBack = new Intent(this, ExerciseActivity.class);
			startActivity(intentBack);
		} else if ("testmaxforce".equals(fromWhich)) {
			Intent intentBack = new Intent(this, TestMaxForceActivity.class);
			startActivity(intentBack);
		} else if ("testposition".equals(fromWhich)) {
			Intent intentBack = new Intent(this, TestPositionActivity.class);
			startActivity(intentBack);
		}
		fromWhich = "";
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {

		switch (v.getId()) {
		case R.id.adjust_seat_up:
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				mUpBtn.setBackgroundColor(Color.GREEN);
				try {
					mOutputStream.write(SEAT_COROTATION);
				} catch (IOException e) {
					e.printStackTrace();
					IOMistake();
				}
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				mUpBtn.setBackgroundColor(Color.WHITE);
				try {
					mOutputStream.write(SEAT_ROTATE_STOP);
				} catch (IOException e) {
					e.printStackTrace();
					IOMistake();
				}
			}

			break;

		case R.id.adjust_seat_down:
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				mDownBtn.setBackgroundColor(Color.GREEN);
				try {
					mOutputStream.write(SEAT_REVERSAL);
				} catch (IOException e) {
					e.printStackTrace();
					IOMistake();
				}
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				mDownBtn.setBackgroundColor(Color.WHITE);
				try {
					mOutputStream.write(SEAT_ROTATE_STOP);
				} catch (IOException e) {
					e.printStackTrace();
					IOMistake();
				}
			}
			break;
		default:
			break;
		}

		return false;
	}
	@Override
	protected void onDataReceived(byte[] buffer, int size, final int count) {
		
	}
}
